<template>
  <div class="admin-management">
    <!-- 上部分：筛选条件 -->
    <div class="filter-bar">
      <div class="filter-controls">
        <el-input
            v-model="filterAccount"
            placeholder="用户账号"
            clearable
            style="width: 200px"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select
            v-model="filterStatus"
            placeholder="用户状态"
            clearable
            style="width: 120px"
        >
          <el-option label="全部状态" value="" />
          <el-option label="正常" value="1" />
          <el-option label="停用" value="2" />
        </el-select>
        <el-button type="primary" @click="searchUsers">
          查询
        </el-button>
        <el-button @click="resetFilter">
          重置
        </el-button>
      </div>
    </div>

    <!-- 下部分：用户表格 -->
    <div class="table-section">
      <div class="table-header">
        <h3>用户列表</h3>
        <div class="table-controls">
          <el-button size="small" type="success" @click="addNewUser">
            添加用户
          </el-button>
        </div>
      </div>
      <div class="table-container">
        <el-table
            :data="paginatedUserData"
            style="width: 100%; height: 100%;"
            stripe
            :header-cell-style="{ background: '#f8f9fa', color: '#333', fontWeight: '500', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
            border
            v-loading="loading"
        >
          <el-table-column prop="id" label="序号" width="80" align="center" />
          <el-table-column prop="username" label="账号" min-width="150" align="center" />
          <el-table-column prop="identity" label="身份" min-width="80" align="center">
            <template #default="{ row }">
              {{ row.identity === 1 ? '管理员' : '用户' }}
            </template>
          </el-table-column>
          
          <el-table-column prop="taskTypeId" label="任务类型权限" min-width="200" align="center">
            <template #default="{ row }">
              {{ formatTaskTypePermissions(row.taskTypeId) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="状态" width="80" align="center">
            <template #default="scope">
              <el-switch
                v-if="scope.row.identity !== 1"
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="2"
                @change="toggleUserStatus(scope.row)"
                :loading="statusChangingIds.includes(scope.row.id)"
              />
              <el-tag v-else :type="getUserStatusType(scope.row.status)" size="small">
                {{ getUserStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250" align="center" fixed="right">
            <template #default="scope">
              <div class="action-buttons" v-if="scope.row.identity !== 1">
                <el-button size="small" type="warning" @click="editUser(scope.row)">
                  编辑
                </el-button>
                <el-button size="small" type="primary" @click="resetPassword(scope.row)">
                  重置密码
                </el-button>
                <el-button size="small" type="danger" @click="deleteUser(scope.row)">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <div class="pagination-info">
          <span>共 {{ total }} 条记录，当前显示第 {{ (currentPage - 1) * pageSize + 1 }} - {{ Math.min(currentPage * pageSize, total) }} 条</span>
        </div>
        <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            small
        />
      </div>
    </div>

    <!-- 添加/编辑用户弹窗 -->
    <el-dialog
        v-model="showAddDialog"
        :title="isEdit ? '编辑用户' : '添加用户'"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form :model="userForm" label-width="120px" :rules="userRules" ref="userFormRef">
        <el-form-item label="用户账号" prop="username">
          <el-input
              v-model="userForm.username"
              placeholder="请输入用户账号"
              maxlength="20"
              show-word-limit
              :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input
              v-model="userForm.password"
              placeholder="请输入密码"
              type="password"
              show-password
              maxlength="20"
          />
        </el-form-item>
        <el-form-item v-if="!isEdit" label="确认密码" prop="confirmPassword">
          <el-input
              v-model="userForm.confirmPassword"
              placeholder="请再次输入密码"
              type="password"
              show-password
              maxlength="20"
          />
        </el-form-item>
        <el-form-item label="任务类型权限" prop="taskTypeId">
          <el-tree-select
              v-model="userForm.taskTypeId"
              :data="taskTypeOptions"
              :check-strictly="false"
              :render-after-expand="false"
              placeholder="请选择任务类型"
              style="width: 100%"
              multiple
              :show-checkbox="true"
              :check-on-click-node="true"
              @check="handleTreeSelectCheck"
          />
        </el-form-item>
        <el-form-item label="用户状态" prop="status">
          <el-select v-model="userForm.status" placeholder="请选择用户状态" style="width: 100%">
            <el-option label="正常" value="1" />
            <el-option label="停用" value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelEdit">取消</el-button>
        <el-button
            type="primary"
            @click="saveUser"
            :loading="saveLoading"
        >
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { adminAPI,taskTypeAPI } from '../api/index.js'

const router = useRouter()

// 响应式数据
const filterAccount = ref('')
const filterStatus = ref('')
const currentPage = ref(1)
const statusChangingIds = ref([]) // 用于跟踪正在修改状态的用户ID
const pageSize = ref(10)
const total = ref(0)
const showAddDialog = ref(false)
const isEdit = ref(false)
const userFormRef = ref()
const loading = ref(false)
const saveLoading = ref(false)
const taskTypeOptions = ref([])

// 用户列表数据
const userList = ref([])

// 用户表单数据
const userForm = ref({
  id: '',
  username: '',
  password: '',
  confirmPassword: '', // 添加确认密码字段
  taskTypeId: [], // 初始化为空数组
  status: '1'
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户账号', trigger: 'blur' },
    { min: 4, max: 20, message: '账号长度在 4 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    {
      required: () => !isEdit.value, 
      message: '请输入密码', 
      trigger: 'blur'
    },
    {
      min: 6, 
      max: 20, 
      message: '密码长度在6到20个字符之间', 
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        // 检查是否包含数字
        if (!/\d/.test(value)) {
          callback(new Error('密码必须包含数字'));
          return;
        }
        
        // 检查是否包含字母（大小写不限）
        if (!/[a-zA-Z]/.test(value)) {
          callback(new Error('密码必须包含字母'));
          return;
        }
        
        // 检查是否包含特殊字符
        if (!/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value)) {
          callback(new Error('密码必须包含特殊字符'));
          return;
        }
        
        callback();
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    {
      required: () => !isEdit.value, 
      message: '请再次输入密码', 
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== userForm.value.password) {
          callback(new Error('两次输入的密码不一致'));
          return;
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  taskTypeId: [
    { required: true, message: '请选择任务类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择用户状态', trigger: 'change' }
  ]
}

const handleTreeSelectCheck = (checkedNode, { checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys }) => {
  // 获取当前选中的节点
  const currentNode = checkedNode;

  // 如果是第三级节点，不做任何处理（保持只选中当前节点）
  if (!currentNode.children || currentNode.children.length === 0) {
    return;
  }

  // 如果是第一级或第二级节点，自动选中所有子节点
  const getAllChildKeys = (node) => {
    let keys = [];
    if (node.children && node.children.length > 0) {
      node.children.forEach(child => {
        keys.push(child.value);
        keys = keys.concat(getAllChildKeys(child));
      });
    }
    return keys;
  };

  const childKeys = getAllChildKeys(currentNode);

  // 更新选中的keys
  userForm.value.taskTypeId = Array.from(new Set([
    ...userForm.value.taskTypeId,
    ...childKeys
  ]));
};

// 加载用户列表
const loadUserList = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      username: filterAccount.value || '',
      status: filterStatus.value || ''
    };

    const result = await adminAPI.getAdminList(params);

    if (result && result.code === 0) {
      userList.value = result.rows || [];
      total.value = result.total || 0;
    } else {
      throw new Error(result?.msg || '获取用户列表失败');
    }
  } catch (error) {
    console.error('加载用户列表失败:', error);
    ElMessage.error(`加载用户列表失败: ${error.message}`);
    userList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 加载任务类型选项
const loadTaskTypeOptions = async () => {
  try {
    const result = await taskTypeAPI.getTaskTypeList();
    if (result && result.code === 0) {
      // 转换数据格式为el-tree-select需要的结构
      const transformData = (items) => {
        return items.map(item => ({
          value: item.id,  // 使用id作为value
          label: item.typeName,  // 使用typeName作为显示文本
          children: item.children ? transformData(item.children) : []
        }));
      };

      taskTypeOptions.value = transformData(result.data || []);
      console.log('任务类型选项:', taskTypeOptions.value);
    } else {
      throw new Error(result?.msg || '获取任务类型失败');
    }
  } catch (error) {
    console.error('加载任务类型失败:', error);
    ElMessage.error(`加载任务类型失败: ${error.message}`);
    taskTypeOptions.value = [];
  }
};

// 分页数据
const paginatedUserData = computed(() => {
  return userList.value;
});

// 状态显示函数
const getUserStatusType = (status) => {
  const statusMap = {
    '1': 'success',   // 正常
    '2': 'danger'     // 停用
  };
  return statusMap[status] || 'info';
};

const getUserStatusText = (status) => {
  const statusMap = {
    '1': '正常',
    '2': '停用'
  };
  return statusMap[status] || '未知';
};

const formatTaskTypePermissions = (taskTypeId) => {
  if (!taskTypeId) return '无权限'
  
  // 从三级嵌套数组中递归查找ID对应的名称
  const findTaskTypeNameById = (id, options = taskTypeOptions.value) => {
    // 确保id是字符串类型进行比较
    const targetId = String(id);
    
    for (const option of options) {
      // 检查当前级别的选项
      if (String(option.value) === targetId) {
        return option.label;
      }
      
      // 递归检查二级子节点
      if (option.children && option.children.length > 0) {
        for (const childOption of option.children) {
          if (String(childOption.value) === targetId) {
            return childOption.label;
          }
          
          // 递归检查三级子节点
          if (childOption.children && childOption.children.length > 0) {
            for (const grandChildOption of childOption.children) {
              if (String(grandChildOption.value) === targetId) {
                return grandChildOption.label;
              }
            }
          }
        }
      }
    }
    
    return id; // 如果找不到对应名称，返回原始ID
  };
  
  // 将逗号分隔的字符串转换为数组
  let ids = [];
  if (typeof taskTypeId === 'string') {
    ids = taskTypeId.split(',').map(id => id.trim());
  } else if (Array.isArray(taskTypeId)) {
    ids = taskTypeId;
  } else {
    ids = [taskTypeId];
  }
  
  // 遍历ID数组，查找对应的名称
  const names = ids.map(id => findTaskTypeNameById(id));
  
  // 使用顿号连接所有名称
  return names.join('、');
};

// 业务操作函数
const searchUsers = async () => {
  currentPage.value = 1
  await loadUserList()
}

const resetFilter = async () => {
  filterAccount.value = ''
  filterStatus.value = ''
  currentPage.value = 1
  await loadUserList()
  ElMessage.info('已重置筛选条件')
}

const addNewUser = () => {
  isEdit.value = false
  resetForm()
  showAddDialog.value = true
}

const editUser = (row) => {
  isEdit.value = true
  console.log('正在编辑用户，ID:', row);
  userForm.value = {
    id: row.id,
    username: row.username,
    password: '', // 编辑时不显示密码
    taskTypeId: row.taskTypeId ? row.taskTypeId.split(',').map(Number) : [], // 转换为数字数组
    status: row.status.toString() // 确保是字符串
  }

  showAddDialog.value = true
  // 确保树形选择器正确显示已选项
  nextTick(() => {
    if (userFormRef.value) {
      userFormRef.value.clearValidate()
    }
  })
}

const saveUser = async () => {
  try {
    await userFormRef.value.validate(); 
    saveLoading.value = true;

    const userData = {
      username: userForm.value.username,
      password: userForm.value.password || undefined, // 允许空密码
      taskTypeId: userForm.value.taskTypeId.join(','), // 明确转为字符串
      status: userForm.value.status
    };

    let result;
    if (isEdit.value) {
      result = await adminAPI.updateAdmin(userForm.value.id, userData); // 补充更新调用
    } else {
      result = await adminAPI.addAdmin(userData);
    }

    if (result?.code === 0) {
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功');
      showAddDialog.value = false;
      await loadUserList();
    } else {
      throw new Error(result?.msg || '操作失败');
    }
  } catch (error) {
    console.error('保存失败:', error.response?.data || error);
    // 处理表单验证错误
    if (error.name === 'Error' && error.message) {
      ElMessage.error(`操作失败: ${error.message}`);
    } else if (error.response?.data?.msg) {
      ElMessage.error(`操作失败: ${error.response.data.msg}`);
    } else {
      ElMessage.error('操作失败: 请检查输入内容是否正确');
    }
  } finally {
    saveLoading.value = false;
  }
};

const cancelEdit = () => {
  showAddDialog.value = false
  nextTick(() => {
    resetForm()
  })
}

const resetForm = () => {

  userForm.value = {
    id: '',
    username: '',
    password: '',
    confirmPassword: '', // 添加confirmPassword字段重置
    taskTypeId: [], // 初始化为空数组
    status: '1'
  }
  nextTick(() => {
    if (userFormRef.value && typeof userFormRef.value.resetFields === 'function') {
      userFormRef.value.resetFields()
    }
  })
}

const deleteUser = async (row) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除用户"${row.username}"吗？\n\n此操作不可恢复！`,
        '确认删除',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const result = await adminAPI.deleteAdmin(row.id);

    if (result && result.code === 0) {
      ElMessage.success('删除成功');
      await loadUserList();
    } else {
      throw new Error(result?.msg || '删除用户失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error);
      ElMessage.error(`删除用户失败: ${error.message}`);
    }
  }
}

// 切换用户状态函数
const toggleUserStatus = async (row) => {
  try {
    // 添加到正在修改列表中，显示加载状态
    statusChangingIds.value.push(row.id)
    
    // 准备更新数据，只更新状态字段
    const updateData = {
      status: row.status // 直接使用新的状态值
    }
    
    // 调用更新接口
    const result = await adminAPI.updateAdmin(row.id, updateData)
    
    if (result?.code === 0) {
      ElMessage.success(`用户${row.status === 1 ? '启用' : '禁用'}成功`)
      // 重新加载列表以确保数据同步
      await loadUserList()
    } else {
      // 失败时恢复原来的状态
      row.status = row.status === 1 ? 2 : 1
      throw new Error(result?.msg || '更新状态失败')
    }
  } catch (error) {
    console.error('切换用户状态失败:', error)
    ElMessage.error(error.message || '操作失败')
  } finally {
    // 无论成功失败，都从正在修改列表中移除
    statusChangingIds.value = statusChangingIds.value.filter(id => id !== row.id)
  }
}

// 重置用户密码函数
const resetPassword = async (row) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      '确定要重置该用户的密码为默认密码 xxcj@123 吗？',
      '确认重置密码',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 添加到正在修改状态的列表中，显示加载状态
    statusChangingIds.value.push(row.id)
    
    // 调用更新接口，只更新密码字段
    const result = await adminAPI.updateAdmin(row.id, { password: 'xxcj@123' })
    
    if (result?.code === 0) {
      ElMessage.success('密码重置成功')
    } else {
      throw new Error(result?.msg || '密码重置失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置密码失败:', error)
      ElMessage.error(error.message || '操作失败')
    }
  } finally {
    // 无论成功失败，都从正在修改列表中移除
    statusChangingIds.value = statusChangingIds.value.filter(id => id !== row.id)
  }
}

// 分页处理
const handleSizeChange = async (val) => {
  pageSize.value = val
  currentPage.value = 1
  await loadUserList()
}

const handleCurrentChange = async (val) => {
  currentPage.value = val
  await loadUserList()
}

onMounted(async () => {
  await loadTaskTypeOptions();
  await loadUserList();
});
</script>

<style scoped>
/* 保持原有样式不变 */
.admin-management {
  padding: 20px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.filter-bar {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.filter-controls {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.table-controls {
  display: flex;
  gap: 10px;
}

.table-container {
  flex: 1;
  overflow: hidden;
  padding: 0 20px;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-top: 1px solid #f0f0f0;
  flex-shrink: 0;
}

.action-buttons {
  display: flex;
  gap: 5px;
  justify-content: center;
}
</style>
